package win.itshen.cloud.shiro.common.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import win.itshen.cloud.shiro.modules.admin.entity.User;
import win.itshen.cloud.shiro.modules.admin.entity.enums.UserStatus;
import win.itshen.cloud.shiro.modules.admin.service.MenuService;
import win.itshen.cloud.shiro.modules.admin.service.RoleService;
import win.itshen.cloud.shiro.modules.admin.service.UserService;

/**
 * 自定义shiro用户认证
 * @author: stephen.shen
 * @create: 2019-05-22 18:58
 */
@Component
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    /**
     * 权限认证
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        /**
         * 1. 获取当前登录用户信息
         * 2. 获取当前用户关联的角色、权限等
         * 3. 将角色、权限封装到AuthorizationInfo对象中并返回
         */
        //User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(principals == null){
            throw new AuthorizationException("principals should not be null");
        }
        User user = (User) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //获取用户角色
        simpleAuthorizationInfo.setRoles(roleService.findRoleByUserId(user.getId()));
        //获取用户权限
        //List<Menu> menuList = menuService.findUserPermissions(user.getUsername());
        //Set<String> permSet = menuList.stream().map(Menu::getPerms).collect(Collectors.toSet());
        simpleAuthorizationInfo.setStringPermissions(menuService.findPermsByUserId(user.getId()));

        return simpleAuthorizationInfo;
    }

    /**
     * 身份校验
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /**
         * 1. 从token中获取输入的用户名
         * 2. 通过username查询数据库得到用户对象
         * 3. 调用Authenticator进行密码校验
         */
        // 获取用户的输入的账号
        String username = (String) authenticationToken.getPrincipal();
        User user = userService.findByName(username);
        // 账号不存在
        if (user == null) {
            throw new UnknownAccountException();
        }
        // 账号无效
        if (user.getStatus() == UserStatus.INVALID) {
            throw new LockedAccountException();
        }

        // 交给Shiro进行密码的解密校验
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                getName()
        );
        return authenticationInfo;
    }

    /**
     * 设置密码加密方式
     * @param credentialsMatcher
     */
//    @Override
//    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
//
//    }
}
